<template>
    <div class="login-container">
        <div class="login-form">
            <el-form :model="formData" :rules="rules" ref="loginForm">
                <h2 class="title">{{ isLogin ? '登录' : '注册' }}</h2>

                <el-form-item prop="account">
                    <el-input v-model="formData.account" placeholder="请输入账号">
                        <template #prefix><el-icon>
                                <User />
                            </el-icon></template>
                    </el-input>
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password>
                        <template #prefix><el-icon>
                                <Lock />
                            </el-icon></template>
                    </el-input>
                </el-form-item>

                <el-form-item v-if="!isLogin" prop="confirmPassword">
                    <el-input v-model="formData.confirmPassword" type="password" placeholder="确认密码" show-password>
                        <template #prefix><el-icon>
                                <Lock />
                            </el-icon></template>
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm" class="submit-btn" @mousedown.native="playClickSound">
                        {{ isLogin ? '登录' : '注册' }}
                    </el-button>
                    <el-button link @click="toggleFormMode">
                        {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/http'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

const isLogin = ref(true)
const loginForm = ref(null)
const router = useRouter()
const store = useStore()

const formData = reactive({
    account: '',
    password: '',
    confirmPassword: ''
})

const validatePassConfirm = (rule, value, callback) => {
    if (!isLogin.value && value !== formData.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

const rules = {
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePassConfirm, trigger: 'blur' }
    ]
}

const clickSound = new Audio(require('@/assets/audio/click.mp3'))

const playClickSound = () => {
    clickSound.currentTime = 0
    clickSound.play().catch(() => { })
}

const toggleFormMode = () => {
    isLogin.value = !isLogin.value
    formData.confirmPassword = ''
}

const submitForm = async () => {
    try {
        await loginForm.value.validate();

        const apiPath = isLogin.value ? '/user/login' : '/user/register';
        const res = await service.post(apiPath, {
            account: formData.account,
            password: formData.password
        });

        if (res.code === 100) {
            if (isLogin.value) {
                ElMessage.success('登录成功');
                localStorage.setItem('token', res.data);
                sessionStorage.setItem('token', res.data); // 确保存储
                console.log(sessionStorage.getItem('token'));
                router.push('/hall'); // 登录成功后跳转到大厅页面
            } else {
                ElMessage.success(`注册成功！账号：${res.data.account}`);
                toggleFormMode();
            }
        } else {
            ElMessage.error(res.msg);
        }
    } catch (error) {
        console.error('请求失败:', error);
        ElMessage.error(error.response?.data?.msg || '请求失败');
    }
};

</script>

<style scoped>
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: url('@/assets/images/ddz_bg.jpg') no-repeat center/cover;
}

.login-form {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 10px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title {
    text-align: center;
    margin-bottom: 30px;
    color: #409eff;
}

.submit-btn {
    width: 100%;
    margin-top: 10px;
}
</style>